#!/usr/bin/env python
# -*- coding: UTF-8 -*-
'''
@Project ：zhcx-service-test 
@File    ：grading_base_way.py
@Author  ：关依林
@Date    ：2023/8/15 17:23 
'''
from testcases.ProductGrading_Strategy.AmazonListing.service.listing_grading_public_way import *
from testcases.ProductGrading_Strategy.AmazonListing.dao.query_sql_method import *
# from testcases.ProductGrading_Strategy.public_dispatch_way import *


def gradingTemplateListingTypeTest(templateRule, templateRuleValue, cursor, cursorData, orderSourceId):
    filedType1, filedType2, filedType3 = templateRule
    templateRuleValue1, templateRuleValue2, templateRuleValue3 = templateRuleValue
    matchingSkuId = []
    tempList = []
    isFirst  = True
    id = getListingBaseId(orderSourceId)
    listingId = getSubmeterListingDataID(cursor, id, orderSourceId)

    if filedType1:
        for dataId in range(0, len(listingId), 1000):
            data = listingId[dataId: dataId + 1000]
            if 5476461 in data:
                print("stop")
            sliceData = getSliceData(id, cursor, filedType1, data=listingId[dataId: dataId + 1000])
            tempMatchingSku = filterCondition1(sliceData, templateRuleValue1, cursorData)
            matchingSkuId += tempMatchingSku
        isFirst = False

    if filedType2:
        if not isFirst: listingId = matchingSkuId
        for filed in filedType2:
            tempList = []
            country = ""
            if filed == "tag_id":
                value = templateRuleValue2[0]["holiday_tag"]
                base = "t_amazon_listing_tag_"
                ids = ["msku","tag_id"]
            else:
                country = "us"
                value = [i["rating_start"] for i in templateRuleValue2 if "rating_start" in i.keys()][0]
                base = "t_amazon_listing_extra_parent_asin_"
                ids = ["asin", "rating_star"]
            for dataId in range(0, len(listingId), 1000):
                batchData = listingId[dataId: dataId + 1000]
                if isFirst:
                    batchData = getSliceOrderSourceSkuListing(id, cursor, batchData)
                if base == "t_amazon_listing_tag_" : batchDataTemp = [i["msku"] for i in batchData]
                else: batchDataTemp = list(set([i["asin"] for i in batchData]))
                data = getHolidayStarListingData(cursor, id, orderSourceId, batchDataTemp, base, ids, country)
                if filed == "tag_id":
                    tempMatchingSku = filterTemplateCondition(filed, data, value, ids)
                    tempMatchingSku = list(filter(lambda x: x["msku"] in [i["msku"] for i in tempMatchingSku], batchData))
                else:
                    tempMatchingSku = filterCondition3(data, value, batchData)
                tempList += tempMatchingSku
            isFirst = False
            listingId = tempList
        matchingSkuId = tempList

    if filedType3:
        if not isFirst: listingId = matchingSkuId
        tempList = []
        for dataId in range(0, len(listingId), 1000):
            batchData = listingId[dataId: dataId + 1000]
            if isFirst:
                batchData = getSliceOrderSourceSkuData(id, cursor, batchData)
            sliceData = getSliceDataMongo(orderSourceId, batchData=[item["msku"] for item in batchData])
            tempMatchingSku = filterFbaListingCondition(sliceData, templateRuleValue3)
            tempList += tempMatchingSku
        matchingSkuId = [{"source_id":i["order_source_id"], "msku":i["order_source_sku"]} for i in tempList]

    matchingSkuId = [(i["source_id"], i["msku"]) for i in matchingSkuId]
    return matchingSkuId


def gradingTemplateFbaType(templateRule, templateRuleValue, cursorListing, orderSourceId):
    filedType, filedTypeOther = templateRule
    templateRuleValue, templateRuleValueOther = templateRuleValue

    isFirst = True
    matchingSkuId = []
    id = getListingBaseId(orderSourceId)
    listingId = getSubmeterListingDataID(cursorListing, id, orderSourceId)
    if listingId:

        if filedType:
            tempDataList = filterConditionInit(
                id, orderSourceId, listingId, templateRuleValue, cursorListing
            )
            matchingSkuId = filterCondition4(tempDataList, matchingSkuId)
            isFirst = False

        if filedTypeOther:
            if isFirst == True or matchingSkuId != []:
                cursorWareHouse = connectMysql("Java_strategyWarehouse_Test")
                for rule in templateRuleValueOther:
                    # 是否首次执行, 是则通过listingId获取OrderSourceSku
                    if isFirst:
                        tempDataList = filterOtherConditionInit(
                            orderSourceId, rule, listingId, cursorWareHouse, cursorListing, isFirst
                        )
                        matchingSkuId += tempDataList
                        if not matchingSkuId:
                            break
                    # 是否首次执行, 否则通过matchingSkuId获取OrderSourceSku
                    else:
                        tempDataList = filterOtherConditionInit(
                            orderSourceId, rule, matchingSkuId, cursorWareHouse, cursorListing, isFirst
                        )
                        # tempDataList = [(i["source_id"], i["msku"]) for i in tempDataList]
                        matchingSkuId = tempDataList
                        if not matchingSkuId:
                            break
                    isFirst = False

    matchingSkuId = [(i["source_id"], i["msku"]) for i in matchingSkuId]
    return matchingSkuId


def gradingTemplateOrderType(templateRule, templateRuleValue, cursorListing, id, orderSourceId):

    isFirst = True
    matchingSku = []
    filedType, filedTypeOther = templateRule
    templateRuleValue, templateRuleValueOther = templateRuleValue
    dataCursor = connectMysql("Java_strategyData_Test")
    country = getSourceCountry(dataCursor, orderSourceId)
    listingId = getSubmeterListingDataID(cursorListing, id, orderSourceId)

    if listingId:

        if filedType:
            if "asin_first_order_time" in filedType or "first_order_time" in filedType:
                filed = [i for i in filedType if i == "asin_first_order_time" or i == "first_order_time"]
                tempDataList = filterOrderConditionInit(
                    orderSourceId, filed, listingId, templateRuleValue, cursorListing, isFirst, country
                )
                matchingSku = tempDataList
                if not matchingSku: return matchingSku
                isFirst = False

            if "sale_num" in filedType:
                mark = True
                customParam = [json.loads(item["condition_value"])["customParam"]
                               for item in templateRuleValue if item["condition_field"] == "sale_num"][0]
                filed = getQueryFiled(customParam)
                if isFirst:
                    tempDataList = filterOrderConditionInit(
                        orderSourceId, filed, listingId, templateRuleValue, cursorListing, isFirst, country, mark
                    )
                    matchingSku = tempDataList
                else:
                    tempDataList = filterOrderConditionInit(
                        orderSourceId, filed, matchingSku, templateRuleValue, cursorListing, isFirst, country, mark
                    )
                    matchingSku = tempDataList
                if not matchingSku: return matchingSku
                isFirst = False

        if filedTypeOther:
            if isFirst == True or matchingSku != []:
                orderCursor = connectMysql("Java_strategyOrder_Test")

                for condition in templateRuleValueOther:
                    if isFirst:
                        tempDataList = filterOrderOtherConditionInit(
                            orderSourceId, condition, listingId, cursorListing, orderCursor, isFirst, country
                        )
                    else:
                        tempDataList = filterOrderOtherConditionInit(
                            orderSourceId, condition, matchingSku, cursorListing, orderCursor, isFirst, country
                        )
                    matchingSku = tempDataList
                    if not matchingSku: return matchingSku
                    isFirst = False

    matchingSkuId = [(i["source_id"], i["msku"]) for i in matchingSku]
    return matchingSkuId


def gradingStrategyListingData(orderSourceId, cursorStrategy, cursorData, cursorProduct, cursorListing, strategyRule,strategyID):

    isSpecifySku = getSpecifySkuData(cursorStrategy, strategyID)
    isCondition = getStrategyCondition(cursorStrategy, strategyID)
    isSpecifyCountry = getSpecifyCountryData(cursorStrategy, strategyID)
    isSpecifyProduct = getProductStrategy(cursorStrategy, strategyID)[0]["relation_strategy_ids"]
    isFbaFilter = getSpecifyFbaData(cursorStrategy, strategyID)
    if isSpecifyProduct:
        isSpecifyProduct = json.loads(isSpecifyProduct)

    id = getListingBaseId(orderSourceId)
    sourceCountry = getSourceCountry(cursorData, orderSourceId)

    skuSet = []
    mskuSet = []
    asinSet = []
    listingIdSet = []
    matchingSku = []

    # 判断是否指定站点/渠道
    if isSpecifyCountry:
        targetType = isSpecifyCountry[0]["target_type"]
        value = json.loads(isSpecifyCountry[0]["target_value"])
        if targetType == 0:
            if sourceCountry not in value: return matchingSku
        if targetType == 1:
            if str(orderSourceId) not in value: return matchingSku

    # 先获取来源渠道的Listing_id
    listingSet = getSubmeterListingId(cursorListing, id, orderSourceId)
    listingIdSet += listingSet
    platformNoSale, productRiskLevel = isCondition[0]["platform_no_sale"], isCondition[0]["product_risk_level"]
    ruler_result = []
    if listingIdSet:
        # 获取规则匹配的Listing数据
        ruler_result = TemplateRuleDataPolymerization(
            cursorStrategy, orderSourceId, strategyRule, isFbaFilter, sourceCountry
        )
        if not ruler_result: return []
        isFilter = True
        # 判断是否指定产品分级策略
        skuSet = [i["sku"] for i in ruler_result]
        if isSpecifyProduct:
            isFilter = False
            skuSet = getProductStrategySku(isSpecifyProduct,skuSet)
            if not skuSet: return []
        # 判断是否指定SKU/ASIN/渠道SKU
        if isSpecifySku:
            isFilter = False
            appointType = isSpecifySku[0]["appoint_type"]
            appoints = json.loads(isSpecifySku[0]["appoints"])
            if appointType == 1:
                skuSet += appoints
            else:
                tempSkuSet = mSkuConvertSku(
                    id, orderSourceId, appointType, appoints, cursorListing
                )
                if appointType == 2:
                    mskuSet += tempSkuSet
                if appointType == 3:
                    asinSet += tempSkuSet
        # 判断禁售/风险等级
        if platformNoSale != None and productRiskLevel != None:
            isFilter = False
            tempSet = []
            for sku in range(0, len(skuSet), 1000):
                batchData = tuple(skuSet[sku: sku + 1000])
                if platformNoSale != None:  # 是否平台禁售
                    # 先找到禁售数据
                    batchData = getNoSaleData(
                        cursorProduct, batchData, sourceCountry, platformNoSale
                    )
                if productRiskLevel != None:  # 产品风险等级
                    # 先找到高危数据
                    batchData = getHighRiskLevelData(
                        cursorProduct, batchData, sourceCountry, productRiskLevel
                    )
                tempSet += batchData
            skuSet = tempSet
        if not isFilter:
            ruler_result = list(filter(lambda x:x["sku"] in skuSet, ruler_result))
    ruler_result = [str(i["listing_id"]) for i in ruler_result]

    return ruler_result

